package com.example.mysecurity.service.impl;

import com.example.mysecurity.mapper.MenuMapper;
import com.example.mysecurity.mapper.RoleMapper;
import com.example.mysecurity.mapper.UserMapper;
import com.example.mysecurity.pojo.Menu;
import com.example.mysecurity.pojo.Role;
import com.example.mysecurity.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("执行了com.example.myspringsecurity.service.impl.UserServiceImpl.loadUserByUsername方法");
        User myUser = userMapper.selectUserByName(username);
        /*
         * org.springframework.security.core.userdetails.User为UserDetails接口的实现类。
         * 也可以自定义的User实现UserDetail接口提供对应的属性。
         * */
        if (myUser == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        System.out.println("用户查询存在myUser："+myUser);
        //查询用户拥有的权限
        List<Menu> menus = menuMapper.selectByUserId(myUser.getId());
        ArrayList<GrantedAuthority> list = new ArrayList<>();
        menus.forEach(menu -> {
            //获取的权限为null时，将null添加到SimpleGrantedAuthority会出现
            //A granted authority textual representation is required异常信息
            String permission = menu.getPermission();
            if (permission != null && permission!=""){
                list.add(new SimpleGrantedAuthority(permission));
            }
        });
        //查询用户所有角色
        List<Role> roles = roleMapper.selectByUserId(myUser.getId());
        roles.forEach(role -> {
            list.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
        });

        //参数一：用户名  参数二：密码  参数三：权限（暂时不授权，创建个没有元素集合。不能指定null）
        org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(
                myUser.getUsername(), myUser.getPassword(), list);
        System.out.println("return user :"+user);
        return user;
    }
}
